package com.hk.Mgr.web.controller.app;

import com.hk.Mgr.web.dto.IFACreate;
import com.hk.Mgr.web.dto.IfaInformation;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.CardStatusCode;
import com.hk.commons.HqlFilter;
import com.hk.commons.ResultCode;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.sys.SysUser;
import com.hk.service.kyc.IAgreement;
import com.hk.service.order.IPayment;
import com.hk.service.sys.ISysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
@RequestMapping(value = BaseCtrl.App + "/ifaCtrl")
public class AppIFACtrl extends BaseCtrl {

    @Autowired
    private ISysUser sysUserService;

    @Autowired
    private IAgreement agreementService;

    @Autowired
    private IPayment paymentService;

    @Value("${ifa.baseUrl}")
    private String IFA_BASE_URL;

    @Value("${qingniu.pdf}")
    private String QINIU_BASE_URL;

    @ResponseBody
    @RequestMapping(value = "/createIFA", method = RequestMethod.POST)
    public ResponseBase createIFA(@RequestBody IFACreate ifaCreate) {
        ResponseBase responseBase = new ResponseBase();

        if (StringHelper.isBlank(ifaCreate.getUserId())) {
            responseBase.setResultCode(ResultCode.PARAM_ERROR.getCode());
            responseBase.setMsg("参数不能为空");

            return responseBase;
        }


        Long userId = Long.valueOf(ifaCreate.getUserId());

        Payment payment = paymentService.getIfaPayment(userId);


        SysUser sysUser = this.sysUserService.findById(userId);

        if (payment == null) {
            responseBase.setResultCode(ResultCode.PARAM_ERROR.getCode());
            responseBase.setMsg("用户信息不全");

            return responseBase;
        }



        try {
            ExecutorService executor = Executors.newFixedThreadPool(1);
            Runnable task = new Runnable() {
                public void run() {
                    String ifaPdfFileName = agreementService.createIFAPdf(sysUser, payment);
                    if (StringHelper.isBlank(ifaPdfFileName)) {
                        logger.info("userName = {}, realName = {}, IFA PDF 协议生成失败", sysUser.getName(), sysUser.getRealName());
                    }else{
                        logger.info("userName = {}, realName = {}, IFA PDF 协议生成成功", sysUser.getName(), sysUser.getRealName());
                        sysUser.setIfaPdfUrl(ifaPdfFileName);
                    }

                    String ifaHtmlFileName =  agreementService.createIFAHtml(sysUser, payment);
                    if (StringHelper.isBlank(ifaHtmlFileName)) {
                        logger.info("userName = {}, realName = {}, IFA HTML 协议生成失败", sysUser.getName(), sysUser.getRealName());
                    }else{
                        logger.info("userName = {}, realName = {}, IFA HTML 协议生成成功", sysUser.getName(), sysUser.getRealName());
                        sysUser.setIfaHtmlUrl(ifaHtmlFileName);
                    }

                    sysUserService.update(sysUser);

                }
            };
            executor.execute(task);
            executor.shutdown();



        } catch (Exception e) {
            e.printStackTrace();
        }

        responseBase.setResultCode(ResultCode.SUCC.getCode());
        responseBase.setMsg("请求成功");
        return responseBase;
    }

    @ResponseBody
    @RequestMapping(value = "/ifa/{userId}", method = RequestMethod.GET)
    public ResponseBase<IfaInformation> ifaInformation(@PathVariable Long userId) {
        ResponseBase<IfaInformation> responseBase = new ResponseBase<>();
        IfaInformation ifaInformation = new IfaInformation();
        ifaInformation.setUrl("");
        ifaInformation.setSign(false);
        ifaInformation.setBind(false);

        if (userId == null) {
            responseBase.setResultCode(ResultCode.PARAM_ERROR.getCode());
            responseBase.setMsg("参数不能为空");
        } else {
            SysUser sysUser = this.sysUserService.findById(userId);

            Payment payment = paymentService.getIfaPayment(userId);

            if (payment != null) {
                ifaInformation.setBind(true);
            }

            if (StringHelper.isNotBlank(sysUser.getIfaHtmlUrl())) {
                ifaInformation.setSign(true);
                ifaInformation.setUrl(QINIU_BASE_URL + sysUser.getIfaHtmlUrl());
            }else{
                ifaInformation.setSign(false);
                ifaInformation.setUrl( IFA_BASE_URL + sysUser.getId());
            }

            responseBase.setResultCode(ResultCode.SUCC.getCode());
            responseBase.setMsg("请求成功");
            responseBase.setResult(ifaInformation);
        }

        return responseBase;
    }


    /**
     * 如果用户的ifa注册协议未生成，则调用此方法
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showIFA/{userId}", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String showIFA(@PathVariable Long userId) {
        String responseBase = "";

        if (userId != null) {

            Payment payment = paymentService.getIfaPayment(userId);

            SysUser sysUser = this.sysUserService.findById(userId);

            if (StringHelper.isNotBlank(sysUser.getIfaHtmlUrl())) {
                return null;
            }

            if (payment != null) {
                logger.info("用户已绑卡");
                String content = this.agreementService.showIFA(sysUser, payment);
                responseBase = content;
            } else {
                logger.info("用户未绑卡");
                String content = this.agreementService.showIFA(sysUser, null);
                responseBase = content;
            }

        }
        return responseBase;
    }

}
